<?php
// +----------------------------------------------------------------------
//            -------------------------
//           /   / ----------------\  \
//          /   /             \  \
//         /   /              /  /
//        /   /    /-------------- /  /
//       /   /    /-------------------\  \
//      /   /                   \  \
//     /   /                     \  \
//    /   /                      /  /
//   /   /      /----------------------- /  /
//  /-----/      /---------------------------/
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://baimifan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: Sage 2016/4/22  16:46
// +----------------------------------------------------------------------
namespace Admin\Controller;
use Think\Model;

class ApplyController extends CashierBaseController {

    function index() {
        $act=M("Activity")->where(["apply_start"=>['lt',date("Y-m-d h:i:s")],"apply_end"=>["gt",date("Y-m-d h:i:s")]])->select();
        $this->assign("act",$act);
        $this->display();
    }

    function doApply() {
        $data = I("post.");
        //非会员先创建临时会员卡
        if($data['style']>0){
            $Card=new \Common\Model\CardModel();
            $info['child_name']=$data['contactor_name'];
            $info['father_phone']=$data['contactor_phone'];
            $info['mother_phone']=$data['contactor_phone'];
            $r=$Card->create($info);
            if(!$r){
                $this->error('系统错误,生成临时会员失败');
            }
            $data['user_id']=$r['user_id'];
        }
        $summary="线下活动报名，报名费活动原价：".I('post.price_apply')."元，打折后：".I('post.price_apply_d')."元，材料费：".I('post.price_material')."元,折后总计：".I('post.money');
        //生成支付订单
        $Pay = M("Pay");
        $Pay->startTrans();
        $map_pay = [
            "user_id" => $data['user_id'] ,
            "status" => 1 ,
            "type" => 4 ,
            "way" => $data['pay_way'] ,
            "summary" => $summary ,
            "money" => $data['money'] ,
            "money_real" =>$data['money_real'] ,
            "money_zero" => $data['money_zero']
        ];
        $pay_id=$Pay->data($map_pay)->add();
        if (!$pay_id) {
            $Pay->rollback();
            $this->error("支付失败,Error:101");
        }
        //生成报名apply
        $Act_apply = M("Activity_apply");
        $map_apply=[
            "activity_id"=>$data['activity_id'],
            "user_id"=>$data['user_id'],
            "pay_id"=>$pay_id,
            "is_applyfree"=>$data['is_applyfree'],
            "discount_apply"=>I('post.discount_apply'),
            'contactor'=>json_encode(['name'=>$data['contactor_name'],'phone'=>str_replace(' ','',$data['contactor_phone'])])
        ];
        $apply_id=$Act_apply->data($map_apply)->add();
        if(!$apply_id){
            $Act_apply->rollback();
            $this->error("支付失败,Error:102");
        }
        //可报名人数减少
        $r=M("Activity")->where(['activity_id'=>$data['activity_id']])->setDec('apply_num',1);
        if(!$r){
            $Act_apply->rollback();
            $this->error("支付失败,Error:103");
        }
        if(I('post.is_applyfree')==1){
            //扣除免活动费次数
            $d=M("Activity")->where(['activity_id'=>$data['activity_id']])->find();
            $rr=M("Card")->where(["card_id"=>$data['card_id']])->setDec('num_activity',$d['num_deduct']);
            if($rr){
                $Score = D("Score");
                $Score->addscore($data['user_id'], "4");
                $Act_apply->commit();
                $this->success("支付成功",U("orderShow","apply_id=".$apply_id));
            }else{
                $Act_apply->rollback();
                $this->error("支付失败,Error:104");
            }
        }else{
            $Score = D("Score");
            $Score->addscore($data['user_id'], "4");
            $Act_apply->commit();
            $this->success("支付成功",U("orderShow","apply_id=".$apply_id));
        }
    }
    //订单打印
    function orderShow() {
        $apply_id = I("get.apply_id");
        $d = [];
        $da = M("View_activity_apply")->where(["apply_id" => $apply_id])->find();
        if(!$da){
            $d=[];
        }else{
            $dp=M('Pay')->where(['pay_id'=>$da['pay_id']])->find();
            $d['order_id'] = $da['apply_id']; //订单号
            $d['pay_id']=$da['pay_id'];  //支付流水号
            $d['money_apply'] = $da['price_apply']; //报名价
            $d['money_material'] = $da['price_material']; //材料价
            $d['money_b'] = $da['price_apply']+$da['price_material'];

            $d['type'] = "活动报名";
            if($da['is_applyfree']==1){
                $d['discount_apply'] = 0; //折扣
            }else{
                $d['discount_apply'] = 1; //折扣
            }
            $d['money'] = $dp['money']; //实际价格
            $d['money_real'] = $dp['money_real']; //实收
            $d['money_zero'] = $dp['money_zero']; //找零
            $d['create_time'] = $dp['create_time']; //找零
            $dc = M("View_activity_apply")->where(["apply_id" => $apply_id])->select();
            $d['list'] = $dc;

            $user_id=$dp['user_id']==''?0:$dp['user_id'];
            $User= new \Common\Model\UserModel();
            $d['card']=$User->getCard($user_id);
            $d['score']=$User->getScore($user_id);
        }
        $this->assign("d" , $d);
        $this->display('Print:orderAct');
    }
    //活动查询-post
    function act_search(){
        $activity_id=I("post.activity_id");
        $d=M("Activity")->where(["activity_id"=>$activity_id])->find();
        $r=[
            "status"=>"success",
            "data"=>$d
        ];
        echo json_encode($r);
    }
    //下单前检查
    function applyCheck(){
        $activity_id=I("post.activity_id");
        $user_id=I("post.user_id");
        $style=I("post.style");
        $d=M("Activity")->where(["activity_id"=>$activity_id])->find();
        if(!$d){
            $r=[
                "status"=>"error",
                "data"=>"不存在此活动"
            ];
            echo json_encode($r);
            return;
        }
        if($style<1){
            $c=M("Activity_apply")->where(["activity_id"=>$activity_id,"user_id"=>$user_id,'is_refund'=>'0'])->count();
            if($c>0){
                $r=[
                    "status"=>"error",
                    "data"=>"此会员卡已报名"
                ];
                echo json_encode($r);
                return;
            }
        }
        if(strtotime($d['apply_start']) > time() || strtotime($d['apply_end']) < time()){
            $r=[
                "status"=>"error",
                "data"=>"不在报名时间内"
            ];
            echo json_encode($r);
            return;
        }
        if($d['apply_num']<=0){
            $r=[
                "status"=>"error",
                "data"=>"报名已满"
            ];
            echo json_encode($r);
            return;
        }else{
            $r=[
                "status"=>"success",
                "data"=>"可报名"
            ];
            echo json_encode($r);
            return;
        }
    }
}